import React, {Component} from 'react'

let editor;


function selectText(text) {
    if (!text) return ;
    if (document.body.createTextRange) {
        var range = document.body.createTextRange()
        range.moveToElementText(text)
        range.select()
    } else if (window.getSelection) {
        var selection = window.getSelection()
        var range = document.createRange()
        range.selectNodeContents(text)
        selection.removeAllRanges()
        selection.addRange(range)
    }
}

class Editor extends Component {

    componentDidMount() {
        let self = this
        if (!editor) {
            editor = new wangEditor('wang-editor');

            editor.config.menus = 
                [ "fontfamily"
                , "fontsize"
                , "|"
                , "forecolor"
                , "bgcolor"
                , "|"
                , "bold"
                , "italic"
                , "underline"
                , "strikethrough"
                , "|"
                , "alignleft"
                , "aligncenter"
                , "alignright"
                ]
            editor.config.pasteText = true;

            // editor.onchange = function () {
            //     self.props.onInput(this.$txt.html(), self.props.focus.split('.'))
            // }

            $('#wang-editor')
                .css('transform', `matrix(${SCALE}, 0, 0, ${SCALE}, 0, 0`)

            editor.create();

            $('.wangEditor-container')
                .on(BROWSER.mouseDown, function (ev) {
                    ev.stopPropagation()
                })
        }
    }

    render() {
        let {isEditing, focus, pages} = this.props
        
        let style = {}

        if (isEditing && focus) {
            style.display = 'block'

            let [p, e] = focus.split('.')
            , elm = pages[p].elements[e]
            , css = elm.css

            style.width = css.width
            style.height = css.height
            style.color = css.color
            style.fontSize = css.fontSize
            style.lineHeight = css.lineHeight

            editor.$txt.html(elm.content)
            selectText(editor.$txt.get(0))

            $('.wangEditor-container')
                .css('top', `${parseInt(css.top) * SCALE}px`)
                .css('left', `${parseInt(css.left) * SCALE}px`)
                .show()
        } else {
            $('.wangEditor-container').hide()
        }

        return (
            <div id="wang-editor" style={style}></div>
        )
    }
}

export default Editor